from src.data_loader import load_events
from src.preprocess import preprocess_events
from src.user_features import extract_user_features
from src.activity_analysis import compute_dau, compute_wau, compute_mau
from src.retention_analysis import compute_retention, generate_labels
from src.visualization import plot_activity, plot_retention
from src.modeling import train_retention_model  # ✅ 新增模型模块引用

import pandas as pd

def main():
    print("📥 正在加载事件数据...")
    df = load_events()

    if df.empty:
        print("❌ 加载失败：events.csv 为空或不存在。")
        return

    print("🔄 正在预处理数据...")
    df = preprocess_events(df)

    print("🧠 正在提取用户特征...")
    user_features = extract_user_features(df)

    print("📈 正在生成用户留存标签...")
    label_df = generate_labels(df, retention_days=3)

    # 处理 user_features
    if 'visitorid' in user_features.index.names:
        if 'visitorid' in user_features.columns:
            user_features = user_features.drop(columns=['visitorid'])
        user_features = user_features.reset_index()

    # 处理 label_df
    if 'visitorid' in label_df.index.names:
        if 'visitorid' in label_df.columns:
            label_df = label_df.drop(columns=['visitorid'])
        label_df = label_df.reset_index()

    print("🔀 正在合并用户特征与标签...")
    user_features = user_features.merge(label_df, on='visitorid', how='left')

    print("📁 正在保存用户特征文件...")
    user_features.to_csv("data/user_features.csv", index=False)

    print("📊 正在计算活跃用户指标（DAU/WAU/MAU）...")
    dau = compute_dau(df)
    wau = compute_wau(df)
    mau = compute_mau(df)

    print("📈 正在计算留存率...")
    retention = compute_retention(df)

    print("📉 正在绘制活跃度图表...")
    plot_activity(dau, wau, mau)

    print("📉 正在绘制留存图表...")
    plot_retention(retention)

    print("🧠 正在训练留存预测模型...")
    train_retention_model(user_features)

    print("✅ 分析与建模全部完成，结果已保存。")

if __name__ == "__main__":
    main()
